package com.LostAndFound.web.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.LostAndFound.domain.Article;
import com.LostAndFound.domain.Category;
import com.LostAndFound.domain.User;
import com.LostAndFound.service.SearchForLoserService;
import com.LostAndFound.utils.CommonsUtils;
import com.google.gson.Gson;

public class SearchForLoserServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	SearchForLoserService service = new SearchForLoserService();
	// 得到要审核的信息
	public void handleCheckLoser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String cid = request.getParameter("cid");
		if(cid==null) {
			cid = "all";
		}
		// 当前页
		int pageNumber = Integer.parseInt(request.getParameter("page"));
		// 每页总条数
		int pageSize = Integer.parseInt(request.getParameter("rows"));
		// 总记录数
		int total = service.getCheckTotalRecordForEasyUI(cid);
		List<Map<String,Object>> mapList = service.getCheckRecordListForSearchLoserToEasyUI(pageNumber,pageSize,cid);
		Gson gson = new Gson();
		String rows = gson.toJson(mapList);
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("{\"total\":"+total+",\"rows\":"+rows+"}");
	}
	// 得到正在进行寻找的信息
	public void recordListForSearchLoser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String cid = request.getParameter("cid");
		if(cid==null) {
			cid = "all";
		}
		// 当前页
		int pageNumber = Integer.parseInt(request.getParameter("page"));
		// 每页总条数
		int pageSize = Integer.parseInt(request.getParameter("rows"));
		// 总记录数
		int total = service.getTotalRecordForEasyUI(cid);
		List<Map<String,Object>> mapList = service.getRecordListForSearchLoserToEasyUI(pageNumber,pageSize,cid);
		Gson gson = new Gson();
		String rows = gson.toJson(mapList);
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("{\"total\":"+total+",\"rows\":"+rows+"}");
	}
	// delete
	public void handleDeleteSearchLoserRecordForEasyUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String aid = request.getParameter("aid");
		boolean success = service.handleDeleteSearchLoserRecordForEasyUI(aid);
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("{\"success\":"+success+"}");
	}
	
	/* add，发布寻找失主记录，规定为管理员发布，即为爱心社部门
	 * jsp隐藏相对的功能，此函数没有用到。2019/03/03
	 * 
	 * 如果要此功能，图片的命名方式建议为"rid_imageName"的形式。
	 * 但jsp没有传递rid，如果实现要传递rid
	 * 
	 */
	@SuppressWarnings({ "unchecked", "static-access" })
	public void handleAddNewSearchLoser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Category category = new Category();
		User user = new User();
		Article article = new Article();
		String imageName = "/search.jpg";
		String cid = "";
		String title = "";
		String detailInfo = "";
		String phone = "";
		try {
			String path_temp = this.getServletContext().getRealPath("images_temp");
			// 1、创建磁盘文件项工厂，设置缓存文件的大小，设置临时文件存储位置
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(1024*1024);
			factory.setRepository(new File(path_temp));
			//2、创建文件上传的核心类
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置上传文件的名称的编码
			upload.setHeaderEncoding("UTF-8");
			// 判断表单是否是文件上传的表单
			boolean multipartContent = upload.isMultipartContent(request);
			if(multipartContent) {
				// 文件上传的表单，解析request获取文件项集合
				List<FileItem> parseRequest = upload.parseRequest(request);
				if(parseRequest!=null) {
					for(FileItem item:parseRequest) {
						// 判断是不是一个普通表单项
						boolean formField = item.isFormField();
						if(formField) {
							// username = zhangsan
							String fieldName = item.getFieldName();
							String fieldValue = item.getString("UTF-8");//对普通表单项的内容进行编码
							if(fieldName.equals("cid")) {
								cid = fieldValue;
							}else if(fieldName.equals("title")) {
								title = fieldValue;
							}else if(fieldName.equals("detailInfo")) {
								detailInfo = fieldValue;
							}else if(fieldName.equals("phone")) {
								phone = fieldValue;
							}
						}else {
							//文件上传项
							String fileName = item.getName();
							InputStream in = item.getInputStream();
							String path_store = this.getServletContext().getRealPath("images");
							OutputStream out = new FileOutputStream(path_store+"/"+fileName);
							IOUtils.copy(in, out);// copy
							imageName="/"+fileName;
							in.close();
							out.close();
							item.delete();
						}
					}
				}
				
			}else {
				// 不是文件上传的表单，普通的获取方式
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}

		//封装article对象
		article.setAid(CommonsUtils.getUUID());
		article.setTitle(title);
		article.setDetailInfo(detailInfo);
		article.setIssueTime(CommonsUtils.getCurrentFormatTime());
		article.setImage(imageName);
		article.setPhone(phone);
		article.setFoundFlag(1);	//foundFlag=1表示未找到
		article.setInvalidFlag(1);	// invalidFlag=1表示未失效
		article.setWhatFlag(0);		//whatFlag=0表示寻找失主
		category.setCid(Integer.parseInt(cid));
		article.setCategory(category);
		user.setUid("0");//设置为爱心社这个部门发布，爱心社是一个特殊的用户，只为显示一些必要信息
		article.setUser(user);
		
		boolean success = service.handleAddNewSearchLoser(article);
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("{\"success\":"+success+"}");
	}
}